//
// File:	EntityFactory.cpp
// Author:	Thomas TISSOT-DUPONT
// E-mail:	<thomas.tissotdupont@free.fr>
// Create:	01/02/2010 20:10:36
// Purpose:	
//
#include "Base.hpp"
#include "EntityFactory.hpp"
#include "Animating.hpp"
#include "Trace.hpp"

//------------------------------------------------------------------
// Constructor / Destructor
//------------------------------------------------------------------
EntityFactory::EntityFactory()
	:	m_dictionary()
{
}

EntityFactory::~EntityFactory()
{
}

//------------------------------------------------------------------
// Register Entity Class
//------------------------------------------------------------------
bool EntityFactory::RegisterEntityClass(const std::string &classname, tPfnEntityCreate pfnCreate)
{
	if (m_dictionary.find(classname) != m_dictionary.end())
	{
		Trace::warning << "EntityFactory::RegisterEntityClass: Duplicate entry for entity type: " << classname << std::endl;
		return false;
	}
	Trace::debug << "EntityFactory::RegisterEntityClass: " << classname << std::endl;
	m_dictionary[classname] = pfnCreate;
	return true;
}

//------------------------------------------------------------------
// Create Entity By Name
//------------------------------------------------------------------
IEntity *EntityFactory::CreateEntityByName(const std::string &classname, const tEntityDatamapKeyValues *pDatamapKeyvalues /* = NULL */)
{
	if (m_dictionary.find(classname) == m_dictionary.end())
	{
		Trace::warning << "EntityFactory::CreateEntityByName: Cannot create entity of type: " << classname << std::endl;
		return NULL;
	}
	IEntity *pEntity = (*m_dictionary[classname])(classname);
	if (pEntity != NULL)
	{
		pEntity->OnCreateDataMap();
		if (pDatamapKeyvalues != NULL)
		{
			tEntityDatamapKeyValues::const_iterator kvIt = (*pDatamapKeyvalues).begin();
			tEntityDatamapKeyValues::const_iterator kvIte = (*pDatamapKeyvalues).end();
			for (; kvIt != kvIte; ++kvIt)
			{
				pEntity->WriteDataMapVariable(kvIt->first, kvIt->second);
			}
		}
		pEntity->OnCreate();
		GlobalVariables::EntityManager::Get().AddEntity(pEntity);
	}
	return pEntity;
}
